from typing import List
from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession

from crud.document import document_compliance_relation as relation_crud
from schemas.document.document_compliance_relation import (
    DocumentComplianceRelationCreate, DocumentComplianceRelationResponse,
    DocumentComplianceRelationWithDetails, BatchRelationCreateRequest
)
from db.session import get_db
from log import log_api, log_error

router = APIRouter(
    prefix="/document-relations",
    tags=["document-relations"]
)


@router.post("/compliance", response_model=DocumentComplianceRelationResponse)
async def create_compliance_relation(
    relation: DocumentComplianceRelationCreate,
    db: AsyncSession = Depends(get_db)
):
    """
    创建文档与检查项的关联
    
    - **document_id**: 文档ID
    - **compliance_template_item_id**: 合规检查项ID
    - **relation_type**: 关联类型（reference参考, evidence证据, template模板）
    """
    log_api(f"创建文档关联: 文档{relation.document_id} -> 检查项{relation.compliance_template_item_id}", module="router.document_relation")
    try:
        # 检查关联是否已存在
        exists = await relation_crud.check_relation_exists(db, relation.document_id, relation.compliance_template_item_id)
        if exists:
            raise HTTPException(status_code=400, detail="该关联关系已存在")
        
        db_relation = await relation_crud.create_relation(db, relation)
        return DocumentComplianceRelationResponse.model_validate(db_relation)
    except HTTPException:
        raise
    except Exception as e:
        log_error(f"创建文档关联失败: {str(e)}", exc_info=True, module="router.document_relation")
        raise HTTPException(status_code=500, detail="创建关联失败")


@router.post("/compliance/batch", response_model=List[DocumentComplianceRelationResponse])
async def batch_create_compliance_relations(
    request: BatchRelationCreateRequest,
    db: AsyncSession = Depends(get_db)
):
    """
    批量创建文档与检查项的关联
    
    - **relations**: 关联关系列表
    
    注意：已存在的关联关系会被跳过
    """
    log_api(f"批量创建文档关联: {len(request.relations)} 个", module="router.document_relation")
    try:
        db_relations = await relation_crud.batch_create_relations(db, request.relations)
        return [DocumentComplianceRelationResponse.model_validate(rel) for rel in db_relations]
    except Exception as e:
        log_error(f"批量创建文档关联失败: {str(e)}", exc_info=True, module="router.document_relation")
        raise HTTPException(status_code=500, detail="批量创建关联失败")


@router.get("/compliance/document/{document_id}", response_model=List[DocumentComplianceRelationResponse])
async def get_document_compliance_relations(
    document_id: UUID,
    db: AsyncSession = Depends(get_db)
):
    """
    获取文档关联的所有检查项
    
    - **document_id**: 文档ID
    """
    log_api(f"获取文档关联的检查项: {document_id}", module="router.document_relation")
    try:
        relations = await relation_crud.get_document_compliance_relations(db, document_id)
        return [DocumentComplianceRelationResponse.model_validate(rel) for rel in relations]
    except Exception as e:
        log_error(f"获取文档关联失败: {str(e)}", exc_info=True, module="router.document_relation")
        raise HTTPException(status_code=500, detail="获取文档关联失败")


@router.get("/compliance/template-item/{compliance_template_item_id}", response_model=List[DocumentComplianceRelationResponse])
async def get_compliance_template_item_documents(
    compliance_template_item_id: UUID,
    db: AsyncSession = Depends(get_db)
):
    """
    获取模板项关联的所有文档
    
    - **compliance_template_item_id**: 合规模板项ID
    """
    log_api(f"获取模板项关联的文档: {compliance_template_item_id}", module="router.document_relation")
    try:
        relations = await relation_crud.get_compliance_template_item_documents(db, compliance_template_item_id)
        return [DocumentComplianceRelationResponse.model_validate(rel) for rel in relations]
    except Exception as e:
        log_error(f"获取检查项关联失败: {str(e)}", exc_info=True, module="router.document_relation")
        raise HTTPException(status_code=500, detail="获取检查项关联失败")


@router.delete("/compliance/{relation_id}")
async def delete_compliance_relation(
    relation_id: UUID,
    db: AsyncSession = Depends(get_db)
):
    """
    删除关联关系
    
    - **relation_id**: 关联关系ID
    """
    log_api(f"删除文档关联: {relation_id}", module="router.document_relation")
    try:
        success = await relation_crud.delete_relation(db, relation_id)
        if not success:
            raise HTTPException(status_code=404, detail="关联关系不存在")
        
        return {"message": "关联关系删除成功"}
    except HTTPException:
        raise
    except Exception as e:
        log_error(f"删除文档关联失败: {str(e)}", exc_info=True, module="router.document_relation")
        raise HTTPException(status_code=500, detail="删除关联失败")


@router.get("/compliance/type/{relation_type}", response_model=List[DocumentComplianceRelationWithDetails])
async def get_relations_by_type(
    relation_type: str,
    db: AsyncSession = Depends(get_db)
):
    """
    根据关联类型获取关联关系
    
    - **relation_type**: 关联类型（reference, evidence, template）
    """
    log_api(f"按类型获取文档关联: {relation_type}", module="router.document_relation")
    try:
        relations = await relation_crud.get_relations_by_type(db, relation_type)
        
        # 构建带详细信息的响应
        detailed_relations = []
        for relation in relations:
            detailed_relation = DocumentComplianceRelationWithDetails(
                id=relation.id,
                document_id=relation.document_id,
                compliance_template_item_id=relation.compliance_template_item_id,
                relation_type=relation.relation_type,
                created_at=relation.created_at,
                document_title=relation.document.title if relation.document else None,
                document_filename=relation.document.filename if relation.document else None,
                compliance_template_item_title=getattr(relation.compliance_template_item, 'title', None),
                compliance_template_item_code=getattr(relation.compliance_template_item, 'code', None)
            )
            detailed_relations.append(detailed_relation)
        
        return detailed_relations
    except Exception as e:
        log_error(f"按类型获取文档关联失败: {str(e)}", exc_info=True, module="router.document_relation")
        raise HTTPException(status_code=500, detail="获取关联关系失败")


@router.delete("/compliance/document/{document_id}")
async def delete_document_relations(
    document_id: UUID,
    db: AsyncSession = Depends(get_db)
):
    """
    删除文档的所有关联关系
    
    - **document_id**: 文档ID
    
    通常在删除文档时调用
    """
    log_api(f"删除文档的所有关联: {document_id}", module="router.document_relation")
    try:
        deleted_count = await relation_crud.delete_document_relations(db, document_id)
        return {
            "message": f"成功删除 {deleted_count} 个关联关系",
            "deleted_count": deleted_count
        }
    except Exception as e:
        log_error(f"删除文档关联失败: {str(e)}", exc_info=True, module="router.document_relation")
        raise HTTPException(status_code=500, detail="删除文档关联失败")


@router.delete("/compliance/template-item/{compliance_template_item_id}")
async def delete_compliance_template_item_relations(
    compliance_template_item_id: UUID,
    db: AsyncSession = Depends(get_db)
):
    """
    删除模板项的所有关联关系
    
    - **compliance_template_item_id**: 合规模板项ID
    
    通常在删除模板项时调用
    """
    log_api(f"删除模板项的所有关联: {compliance_template_item_id}", module="router.document_relation")
    try:
        deleted_count = await relation_crud.delete_compliance_template_item_relations(db, compliance_template_item_id)
        return {
            "message": f"成功删除 {deleted_count} 个关联关系",
            "deleted_count": deleted_count
        }
    except Exception as e:
        log_error(f"删除检查项关联失败: {str(e)}", exc_info=True, module="router.document_relation")
        raise HTTPException(status_code=500, detail="删除检查项关联失败")
